<?php

namespace App\Http\Controllers;

trait CurlTrait {
  private static $TIMEOUT_SECONDS = 30;

  protected function curlCallGet($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$TIMEOUT_SECONDS);
        curl_setopt($ch, CURLOPT_TIMEOUT, self::$TIMEOUT_SECONDS);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');
        $res = curl_exec($ch);

        if ($res === false) {
          $res = [
            'error' => true,
            'message' => curl_error($ch)
          ];
          return json_encode($res);
        }
      //var_dump(curl_error($ch));
      //var_dump($res);exit;
      return $res;
  }

  protected function curlCallPost($url, $param) {
      $ch = curl_init($url);

      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$TIMEOUT_SECONDS);
      curl_setopt($ch, CURLOPT_TIMEOUT, self::$TIMEOUT_SECONDS);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-type: application/json'
      ));
      curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');

      $res = curl_exec($ch);

      if ($res === false) {
          $res = [
              'error' => true,
              'message' => curl_error($ch)
          ];
          $res = json_encode($res);
      }

      return $res;
  }
}